<?php

/* check that user is logged in */
require './login_check.php';

/* connect to mysql db */
require_once './db_connection.php';


$sql_checkid = "SELECT greenhouseid FROM greenhouse WHERE user_id=? AND greenhouseid=?";
$sql_rename = "UPDATE greenhouse SET name=? WHERE greenhouseid=?";
$sql_remove = "DELETE FROM greenhouse WHERE greenhouseid=?";

function remunit($unitid) {
	global $db, $sql_remove;
	
	try {
		$ps = $db->prepare($sql_remove);
		$ps->execute(array($unitid));
	} catch(Exception $e) {
		die("Chyba SQL [remove unit]");
	}
	return;
}

function renunit($unitid, $name) {
	global $db, $sql_rename;
	
	try {
		$ps = $db->prepare($sql_rename);
		$ps->execute(array($name, $unitid));
	} catch(Exception $e) {
		die("Chyba SQL [rename unit]");
	}
	return;
}



/**
 * Check unit owner
 *
 * @param int $unitid Greenhouse ID
 * @param int $userid User ID
 * @return BOOL User is owner
 */
function checkid($unitid, $userid) {
	global $db, $sql_checkid;

	try {
		$pscheck = $db->prepare($sql_checkid);
		$pscheck->execute(array($userid, $unitid));
		$result = $pscheck->fetch(PDO::FETCH_ASSOC);
		if(empty($result)) {
			return FALSE;
		} else {
			return TRUE;
		}
	} catch(Exception $e) {
		die("Chyba SQL [check id]");
	}
}

/*
 *
 *  BODY
 * 
 */

/* get data */
$unitid = $_POST['unitid'];

/* check that unit id corresponds with user id */

if(!checkid($unitid, $_SESSION['user_id'])) {
	die("!! ACCESS DENIED !!");
}
echo("user check ok<br>");

/* do the action */
if(!empty($_POST['rename'])) {
	echo("rename");
	renunit($unitid, $_POST['unitname']);

} else {
	echo("remove");
	remunit($unitid);
}


header("Location: http://".$_SERVER["HTTP_HOST"]."/user.php");
	
exit();
?>
